package cn.com.fstar.demo.service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.com.fstar.framework.base.dao.BaseDaoI;
import cn.com.fstar.framework.base.model.EasyUIComboTree;
import cn.com.fstar.framework.base.model.EasyUIDataGrid;
import cn.com.fstar.core.CodeConstant;
import cn.com.fstar.core.model.Tcontent;
import cn.com.fstar.core.model.TcontentAttachment;
import cn.com.fstar.core.pageModel.Attachment;
import cn.com.fstar.core.pageModel.Content;
import cn.com.fstar.core.pageModel.PageHelper;
import cn.com.fstar.core.pageModel.UploadFileModel;
import cn.com.fstar.core.util.StringUtil;

/**
 * 描述: TODO
 * 
 * @author
 * @date 2016年4月18日 下午5:00:05
 */
@Service
public class ContentService {
    private static final Logger LOG = Logger.getLogger(ContentService.class);
    @Autowired
    private BaseDaoI<Tcontent> contentDao;
    @Autowired
    private BaseDaoI<TcontentAttachment> attachDao;

    public EasyUIDataGrid dataGrid(PageHelper ph) {

        List<Content> rl = new ArrayList<Content>();
        List<Tcontent> tl = null;
        Map<String, Object> params = new HashMap<String, Object>();
        String hql = null;

        hql = "from Tcontent t";
        tl = contentDao.find(hql, params, ph.getPage(), ph.getRows());
        if (tl == null || tl.size() <= 0) {
            return null;
        }

        for (Tcontent t : tl) {
            Content r = new Content();
            if (t.getPublishTime() != null) {
                r.setPublishTimeStr(t.getPublishTime().toString().substring(0, 10));
            }
            if (t.getCreateTime() != null) {
                r.setPublishTimeStr(t.getCreateTime().toString().substring(0, 10));
            }
            if (t.getUpdateTime() != null) {
                r.setPublishTimeStr(t.getUpdateTime().toString().substring(0, 10));
            }

            BeanUtils.copyProperties(t, r);
            rl.add(r);
        }

        EasyUIDataGrid dg = new EasyUIDataGrid();
        dg.setRows(rl);
        dg.setTotal(contentDao.count("select count(*)" + hql, params));
        return dg;
    }

    /* 通过id获取内容 */
    public Content getById(String id) {

        Tcontent tdemoContent = contentDao.get(Tcontent.class, id);
        Content demoContent = new Content();
        BeanUtils.copyProperties(tdemoContent, demoContent);
        // 数据回填时间
        if (tdemoContent.getCreateTime() != null) {
            demoContent.setCreateTimeStr(String.valueOf(tdemoContent.getCreateTime()));
        }
        if (tdemoContent.getPublishTime() != null) {
            demoContent.setPublishTimeStr(String.valueOf(tdemoContent.getPublishTime()));
        }
        if (tdemoContent.getUpdateTime() != null) {
            demoContent.setUpdateTimeStr(String.valueOf(tdemoContent.getUpdateTime()));
        }
        Set<TcontentAttachment> setAttachment = tdemoContent.getTcontentAttachments();
        // 判断附件是否为空，不空则添加到内容表里面
        if (setAttachment != null && setAttachment.size() >= 0) {
            List<Attachment> listAttachment = new ArrayList<Attachment>();
            for (TcontentAttachment attach : setAttachment) {
                Attachment attachment = new Attachment();
                attachment.setTdemoContentId(demoContent.getId());
                attachment.setId(attach.getId());
                attachment.setName(attach.getName());
                listAttachment.add(attachment);
            }
            demoContent.setAttachsPage(listAttachment);
        }

        return demoContent;
    }

    /* 编辑功能 */
    public String edit(Content demoContent) {

        if (demoContent == null) {
            return "error";
        }
        Tcontent tcontent = new Tcontent();
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        try {

            if (StringUtils.isNotBlank(demoContent.getCreateTimeStr())) {
                tcontent.setCreateTime(sf.parse(demoContent.getCreateTimeStr()));
            }
            if (StringUtils.isNotBlank(demoContent.getPublishTimeStr())) {
                tcontent.setPublishTime(sf.parse(demoContent.getPublishTimeStr()));
            }
            if (StringUtils.isNotBlank(demoContent.getUpdateTimeStr())) {
                tcontent.setUpdateTime(sf.parse(demoContent.getUpdateTimeStr()));
            }
        } catch (ParseException e) {
            LOG.error(e.getMessage());
        }

        BeanUtils.copyProperties(demoContent, tcontent);

        if (demoContent.getAttachs().size() > 0) {
            for (UploadFileModel uploadFileModel : demoContent.getAttachs()) {
                TcontentAttachment tAttachment = new TcontentAttachment();
                tAttachment.setTcontent(tcontent);
                tAttachment.setName(uploadFileModel.getFileName_old());
                tAttachment.setOrderNum(1);
                tAttachment.setSize(Long.toString(uploadFileModel.getSize()));
                tAttachment.setLink(uploadFileModel.getFilePath());

                tAttachment.setId(StringUtil.generateUUID());
                tAttachment.setCreateTime(new Date());
                tAttachment.setCreateUser(demoContent.getCreateUser());
                attachDao.save(tAttachment);
            }
        }

        contentDao.update(tcontent);
        return "success";
    }

    /**
     * 是否外链： 0 非外链 1 外链
     * 
     * @return comtree
     */
    public List<EasyUIComboTree> outLinkComboTree() {

        List<EasyUIComboTree> contentList = new ArrayList<EasyUIComboTree>();

        for (int i = 0; i < 2; i++) {
            EasyUIComboTree tree = new EasyUIComboTree();
            tree.setId(String.valueOf(i));
            tree.setText((i == 0 ? CodeConstant.NOTOUTLINK : CodeConstant.OUTLINK));
            contentList.add(tree);
        }

        return contentList;
    }

    /**
     * 状态 0：未发布，1：发布，9：删除
     * 
     * @return comtree
     */
    public List<EasyUIComboTree> statusComboTree() {
        String[] status = { CodeConstant.CONTSTATUS_NOTSENTED, CodeConstant.CONTSTATUS_SENT,
                CodeConstant.CONTSTATUS_DELETE };
        List<EasyUIComboTree> contentList = new ArrayList<EasyUIComboTree>();
        for (int i = 0; i < 3; i++) {
            EasyUIComboTree tree = new EasyUIComboTree();
            tree.setId(String.valueOf(i));
            tree.setText(status[i]);
            contentList.add(tree);
        }
        return contentList;
    }

    public Content get(String id) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("id", id);

        List<Tcontent> ts = contentDao.find("select distinct t from Tcontent t  where t.id = :id ", params);

        Content u = new Content();
        if (ts != null && ts.size() > 0) {
            Tcontent t = ts.get(0);

            BeanUtils.copyProperties(t, u);

            Set<TcontentAttachment> tattachStandards = t.getTcontentAttachments();
            if (tattachStandards != null) {
                for (TcontentAttachment tattachStandard : tattachStandards) {
                    Attachment attachStandard = new Attachment();
                    BeanUtils.copyProperties(tattachStandard, attachStandard);
                    attachStandard.setTdemoContentId(u.getId());
                    u.getAttachsPage().add(attachStandard);
                }
            }
        }

        return u;
    }

    /* 添加nr */
    public String add(Content demoContent) {

        Tcontent t = new Tcontent();
        BeanUtils.copyProperties(demoContent, t);
        // 添加 创建时间 发布时间 修改时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            if (StringUtils.isNotBlank(demoContent.getCreateTimeStr())) {
                t.setCreateTime(sdf.parse(demoContent.getCreateTimeStr()));
            }
            if (StringUtils.isNotBlank(demoContent.getUpdateTimeStr())) {
                t.setUpdateTime(sdf.parse(demoContent.getUpdateTimeStr()));
            }
            if (StringUtils.isNotBlank(demoContent.getPublishTimeStr())) {
                t.setPublishTime(sdf.parse(demoContent.getPublishTimeStr()));
            }
        } catch (ParseException e) {
            LOG.error(e);

        }
        String msg = "";
        t.setId(StringUtil.generateUUID());
        contentDao.save(t);
        msg = "success";
        return msg;
    }

    /**
     * 删除操作
     * 
     * @param id
     */
    public void delete(String id) {
        Tcontent t = contentDao.get(Tcontent.class, id);
        contentDao.delete(t);
    }

}